<?php

class MemberModel extends Model{

    
    function getUserInfo($uid){
        $where['member_id'] = $uid;
        $info = $this->field('member_id,email,auth,nick,name,phone,rmb,forzen_rmb,head,auth_level')->where($where)->find();
        if($info){
            return $info;
        }
        return false;
    }


    /**
     * 登录用户
     * @param int $userId ID
     * @return bool 登录状态
     */
    public function setLogin($userId)
    {
        // 更新登录信息
        $data = array(
            'login_time' => NOW_TIME,
            'login_ip' => get_client_ip(),
        );
        $this->where(array('member_id'=>$userId))->save($data);
        //设置cookie
        $auth = array(
            'member_id' => $userId,
        );
        Session::set('home_user', $auth);
        $auth['code'] = md5(Yaf\Application::app()->getConfig()->application->auto_key);
        Session::set('home_user_sign', data_auth_sign($auth));
        return true;
    }

    /**
     * 检测用户是否登录
     * @return int 用户ID
     */
    public function checkLogin(){
        $user = Session::get('home_user');
        if (empty($user)) {
            return 0;
        } else {
            $user['code'] = md5(Yaf\Application::app()->getConfig()->application->auto_key);
            return Session::get('home_user_sign') == data_auth_sign($user) ? $user['member_id'] : 0;
        }
    }

    public function loginOut(){
        Session::del('home_user');
        Session::del('home_user_sign');
    }

    public function modify($member_id,$data){
        $this->startTrans();
        $version = $this->where(array('member_id'=>$member_id))->getField('version');
        if($data['member_id']) unset($data['member_id']);
        $data['version'] = $version+1;
        $result = $this->where(array('member_id'=>$member_id,'version'=>$version))->save($data);
        if($result){
            $this->commit();
            return true;
        }else{
            $this->rollback();
            return false;
        }
    }

    public static function log($member_id,$text='',$status=1,$action=''){
        if($member_id<=0) return false;
        if(!$action) $action = MODULE_NAME.'/'.CONTROLLER_NAME.'/'.ACTION_NAME;
        $data = array(
            'member_id'=>$member_id,
            'login_ip'=>get_client_ip(),
            'login_time'=>time(),
            'http_user_agent'=>$_SERVER['HTTP_USER_AGENT'],
            'action'=>$action,
            'status'=>$status,
            'text'=>is_string($text)?$text:json_encode($text),
        );
        $model = new Model('MemberLog');
        $model->add($data);
    }

    public function get_field($member_id,$field='member_id'){
        return $this->where(array('member_id'=>$member_id))->getField($field);
    }


}